package com.sky.controller.admin;

import com.sky.config.Ossconfig;
import com.sky.utils.AliOssUtil;
import com.sky.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.sky.result.Result;

import javax.annotation.Resource;

@Slf4j
@RequestMapping("/admin/common")
@RestController
public class UploadController {
    @Resource
    private AliOssUtil aliOssUtil;
   @PostMapping("/upload")
    public Result uploadpicture(MultipartFile file)
   {
       try {

           //随机生成文件名，防止在bucket中覆盖文件
           //获取文件原始名称
           String originalFilename = file.getOriginalFilename();
           //获取文件名后缀
           String hz = originalFilename.substring(originalFilename.lastIndexOf("."));
           //生成随机文件名
           String s = UUIDUtil.getUUid();
           //拼接文件名
           String objectfilename = s + hz;
           //调用upload方法上传文件
           String path =aliOssUtil.upload(file.getBytes(),objectfilename);
           //成功 返回Oss bucket上传路径
           return Result.success(path);//Result.success(path) 返回给前端，前端可以根据这个路径请求到图片并显示
       }catch (Exception e)
       {
           log.error("文件上传失败{}",e.getMessage());
           return Result.error(e.getMessage());
       }
   }
}
